<template>
  <div class="layout-container confidence-evaluate">
    <TagIcon
      :title="`${route.query.sampleName}的置信度评估结果展示`"
      :style="tagIconStyle"
    />

    <BaseInfoForm :showTitle="true" :sampleId = "route.query.sampleId"/>

    <div class="layout-container-table">
      <CommonTable
        :data="state.tableData"
        v-model:page="page"
        :total="total"
        v-loading="loading"
        :showPagination="false"
        :showSelection="false"
        :showIndex="false"
        @span-method="objectSpanMethod"
        @onQuery="onQuery"
      >
        <el-table-column prop="evaluateMetric" label="抗干扰性能评估指标"/>
        <el-table-column prop="performanceResult" label="系统推算数据" />
        <el-table-column prop="realMetric" label="试验真实数据" />
        <el-table-column prop="deviationPercentage" label="偏差百分比" />
        <el-table-column prop="confidenceLevel" label="置信度" />
        <el-table-column prop="unit" label="单位" />
      </CommonTable>
    </div>

    <div class="step-buttons common-buttons">
      <el-button type="primary" @click="onBack">返回</el-button>
      <el-button type="primary" @click="onExport">导出</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import CommonTable from '@/components/common-table/index.vue';
import TagIcon from '@/components/tag-icon/index.vue';
import { Page } from '@/components/common-table/type';
import BaseInfoForm from '../BaseInfoForm/index.vue'
import {
  httpConfidenceEvaluateList,
  httpStartEvaluate,
  httpConfidenceEvaluateResult,
} from '@/api/antiJamPerformCalculateSystem';
import * as XLSX from 'xlsx';
let $router = useRouter();
const route = useRoute();

const tagIconStyle = reactive({ padding: '16px' });
const state = reactive<any>({
  tableData: [],
});
const loading = ref<boolean>(false);
const page = reactive<Page>({
  current: 1,
  pageSize: 20,
});
const total = ref<number>(0);

onMounted(() => {
  onQuery({ pageNo: 1 });
});

// 查询数据
const onQuery = (val: any) => {
  const params = {
    sampleId: route.query.sampleId,
    pageSize: page.pageSize,
    pageNo: page.current,
    ...val,
  };
  loading.value = true;
  httpConfidenceEvaluateResult(params).then((res) => {
    const result = res.data;
    loading.value = false;
    if (result && result.confidenceResult) {
      const { confidenceLevel, deviationPercentage, realMetric } = result.confidenceResult;

      const metricNameMap: { [key: string]: string } = {
        "distFollowAcc": "距离跟踪精度推算结果",
        "discoverDist": "发现距离推算结果",
        "angleFollowAcc": "角度跟踪精度推算结果",
        "hitRate": "命中率推算结果",
        "antiPressRate": "抗压制干扰成功率推算结果",
        "antiCheatRate": "抗欺骗干扰成功率推算结果",
        "vecFollowAcc": "速度跟踪精度推算结果",
        "followDist": "跟踪距离推算结果",
      };

      const rows = Object.keys(confidenceLevel).map((key) => {
        const metricName = key.replace('_confidenceLevel', '');
        return {
          evaluateMetric: metricNameMap[metricName] || metricName,
          performanceResult: result.performanceResult ? result.performanceResult[metricName] : '-',
          realMetric: realMetric[`${metricName}_realMetric`],
          deviationPercentage: deviationPercentage[`${metricName}_deviationPercentage`],
          confidenceLevel: confidenceLevel[key],
          unit: '-' // 可以根据需要添加单位
        };
      });

      state.tableData = rows;
    } else {
      state.tableData = [];
    }

    total.value = state.tableData.length;
  });
};

// 合并列
const objectSpanMethod = (obj: any) => {
  const { row, column, rowIndex, columnIndex } = obj;
};

// 返回
const onBack = () => {
  $router.push({
    path: '/antiJamPerformCalculateSystem/confidenceEvaluate',
    query: {},
  });
}

// 导出
const onExport = () => {
  ElMessageBox.confirm('你确定要导出excel文件吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      downloadFile();
    });
}

// 下载文件
const downloadFile = () => {
  try {
    // 获取表格数据
    const tableData = state.tableData;

    // 定义固定的表头
    const headers = [
      '抗干扰性能评估指标',
      '系统推算数据',
      '试验真实数据',
      '偏差百分比',
      '置信度',
      '单位'
    ];

    // 转换数据
    const exportData = tableData.map((row: any) => {
      return {
        '抗干扰性能评估指标': row.evaluateMetric,
        '系统推算数据': row.performanceResult,
        '试验真实数据': row.realMetric,
        '偏差百分比': row.deviationPercentage,
        '置信度': row.confidenceLevel,
        '单位': row.unit,
      };
    });

    // 创建一个新的工作簿
    const workbook = XLSX.utils.book_new();

    // 将数据转换为工作表
    const worksheet = XLSX.utils.json_to_sheet(exportData, { header: headers });

    // 将工作表添加到工作簿中
    XLSX.utils.book_append_sheet(workbook, worksheet, `${route.query.sampleName}的置信度评估结果`);
   
    // 生成 Excel 文件并下载
    XLSX.writeFile(workbook, `${route.query.sampleName}的置信度评估结果.xlsx`);
  } catch (error) { 
    ElMessage.error('导出失败，请重试');
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/style/buttons';
.confidence-evaluate {
  .layout-container-table {
    .el-button--small {
      background: transparent;
      color: rgba(24, 81, 237, 1);
    }
  }

  .step-buttons {
    display: flex;
    justify-content: center;
    box-shadow: 0px 0px 10px rgba(218, 222, 224, 1);
    padding: 10px 0;
  }
}
.el-button {
    background: rgb(1, 18, 90);
    border: 0;
  }
</style>
